import { Menu } from "antd";
import { useState, useMemo, useEffect } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import { MenuItem, menuItems } from "./menuConfig";

interface Props {
  collapsed?: boolean;
}

export const SideBar: React.FC<Props> = ({ collapsed = false }) => {
  const location = useLocation();
  const navigate = useNavigate();

  const [openKeys, setOpenKeys] = useState<string[]>([]);

  // 将菜单转为 antd 支持的结构
  const convertToAntdItems = (items: MenuItem[]): any[] =>
    items.map((item) => ({
      key: item.key,
      icon: item.icon,
      label: item.label,
      children: item.children ? convertToAntdItems(item.children) : undefined,
    }));

  // 递归找到当前路由对应的 key 和所有父级 key
  const findSelectedAndOpenKeys = (
    items: MenuItem[],
    path: string,
    parentKeys: string[] = []
  ): { selectedKey: string; openKeys: string[] } | null => {
    for (const item of items) {
      if (item.path === path) {
        return { selectedKey: item.key, openKeys: parentKeys };
      }
      if (item.children) {
        const result = findSelectedAndOpenKeys(item.children, path, [...parentKeys, item.key]);
        if (result) return result;
      }
    }
    return null;
  };

  const selectedKeyInfo = useMemo(() => {
    return findSelectedAndOpenKeys(menuItems, location.pathname);
  }, [location.pathname, menuItems]);
  console.log(selectedKeyInfo);

  useEffect(() => {
    if (selectedKeyInfo) {
      setOpenKeys(selectedKeyInfo.openKeys);
    }
  }, [selectedKeyInfo]);

  const handleClick = ({ key }: { key: string }) => {
    // 根据 key 找到 path
    const findPath = (items: MenuItem[]): string | undefined => {
      for (const item of items) {
        if (item.key === key && item.path) return item.path;
        if (item.children) {
          const result = findPath(item.children);
          if (result) return result;
        }
      }
      return undefined;
    };
    const path = findPath(menuItems);
    if (path) navigate(path);
  };

  return (
    <Menu
      mode="inline"
      theme="light"
      style={{ height: "100%", borderRight: "1px solid #eee" }}
      items={convertToAntdItems(menuItems)}
      selectedKeys={selectedKeyInfo ? [selectedKeyInfo.selectedKey] : []}
      openKeys={collapsed ? [] : openKeys}
      onOpenChange={setOpenKeys}
      onClick={handleClick}
    />
  );
};
